import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {Observable, of, switchMap} from 'rxjs';
import {HttpClient} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class AuthGuardGuard implements CanActivate {

  constructor(
    private router: Router,
    private http: HttpClient
  ) {
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    return this.checkLogin().pipe(
      switchMap((result: boolean) => {
          if (!result) {
            this.router.navigateByUrl('login')
          }
          return of(result)
        }
      )
    )
  }

  checkLogin(): Observable<boolean> {
    return this.http.get<boolean>("api/open/checkLoginStatus")
  }

}
